//
//  BiometricsManage.swift
//  Signum
//
//  Created by x-men on 2023/8/1.
//

import Foundation
import LocalAuthentication
import AuthenticationServices

enum ABiometricsSupportType {
    
    case touchID
    
    case faceID
    
    case none
}

//class SIBiometricsManage {
//
//    static let shared = SIBiometricsManage()
//
//    //是否授权了生物识别
//    static func canAuthenticationWithBiometrics() -> Bool {
//        let context = LAContext()
//        var error: NSError? = nil
//        let canEvaluatePolicy = context.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: &error) as Bool
//        if error != nil {
//            print(error!.localizedDescription as String)
//        }
//        if canEvaluatePolicy {
//            return true
//        } else {
//            return false
//        }
//    }
//
//    //获取设备支持生物识别的类型
//    static func getSupportType() -> ABiometricsSupportType {
//        let context = LAContext()
//        //手机至少设置了密码知道类型
//        if context.canEvaluatePolicy(LAPolicy.deviceOwnerAuthentication, error: nil) {
//            if context.biometryType == LABiometryType.touchID {
//                return .touchID
//            } else if context.biometryType == LABiometryType.faceID {
//                return .faceID
//            }
//        }
//        return .none
//    }
//
//    static var isSupportFaceID: Bool {
//        if SIBiometricsManage.getSupportType() == .faceID {
//            return true
//        }
//        return false
//    }
//
//    //调起生物识别
//    func invokeAuthenticationWithBiometrics(_ policy: LAPolicy = LAPolicy.deviceOwnerAuthentication, completeBlock: (()->())?) {
//        let context = LAContext()
//        //记录是否更改了FaceID 或者新增
//        //context.evaluatedPolicyDomainState
//        context.localizedFallbackTitle = "Enter the password"
//        var error: NSError? = nil
//        let canEvaluatePolicy = context.canEvaluatePolicy(policy, error: &error) as Bool
//        var desc = "Verify existing fingerprint"
//        if SIBiometricsManage.isSupportFaceID {
//            desc = "Verify existing faces"
//        }
//        if canEvaluatePolicy {
//            context.evaluatePolicy(policy, localizedReason: desc) { result, error in
//                if result {
//                    DispatchQueue.main.async {//主线程
//                        if let completeBlock = completeBlock {
//                            completeBlock()
//                        }
//                    }
//                    print("SUCCESS!")
//                } else {
//                    self.authFail(error: error)
//                }
//            }
//        } else {
//            //            print(error!.localizedDescription as String)
//            self.authFail(error: error)
//        }
//
//    }
//
//    func authFail(error: Error?) {
//        var desc = ""
//        if let error = error as NSError? {
//            let type = LocalAuthentication.LAError.Code.init(rawValue: error.code)
//            switch(type) {
//            case LocalAuthentication.LAError.systemCancel:
//                //                    print("系统取消授权，如其他APP切入");
//                break;
//            case LocalAuthentication.LAError.userCancel:
//                //                    print("用户取消验证Touch ID");
//                break;
//            case LocalAuthentication.LAError.authenticationFailed:
//                //此处弹框处理
//                //                    print("授权失败");
//                desc = "Please enable the service in \"Settings - \(SIAppManager.shared.getAppDisplayName())\" on your iPhone"
//                DispatchQueue.main.async {//主线程
//                    self.showMessage(desc: desc)
//                }
//                break;
//            case LocalAuthentication.LAError.passcodeNotSet:
//                //此处弹框处理
//                //                    print("系统未设置密码");
//                desc = "Please set the password of your phone."
//                DispatchQueue.main.async {//主线程
//                    self.showMessage(desc: desc)
//                }
//                break;
//            case LocalAuthentication.LAError.biometryNotAvailable:
//                //此处弹框处理
//                //                    print("设备Touch ID不可用，例如未打开");
//                desc = "Please enable the service in \"Settings - \(SIAppManager.shared.getAppDisplayName())\" on your iPhone"
//                DispatchQueue.main.async {//主线程
//                    self.showMessage(desc: desc)
//                }
//                break;
//            case LocalAuthentication.LAError.biometryNotEnrolled:
//                //此处弹框处理
//                //                    print("设备Touch ID不可用，用户未录入");
//                desc = "Biometrics are not available, the current device is not entered."
//                DispatchQueue.main.async {//主线程
//                    self.showMessage(desc: desc)
//                }
//                break;
//            case LocalAuthentication.LAError.userFallback:
//                //                    print("用户选择输入密码，切换主线程处理");
//                break;
//            default:
//                //                    print("其他情况，切换主线程处理");
//                break;
//            }
//        }
//    }
    
//    func showMessage(desc: String) {
//        Alert.showView(withTitle: "Message", message: desc, dismiss: { index in
//        }, cancelButtonIndex: 0, destructiveButtonIndex: 100, titles: ["Confirm"])
//    }
    
//
//}

class ASAuthorizationManage: NSObject,ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
    
    static let shared = ASAuthorizationManage()
    
    // Configure request, setup delegates and perform authorization request
    func handleAuthorizationAppleIDButtonPress() {
        let appleIDProvider = ASAuthorizationAppleIDProvider()
        let request = appleIDProvider.createRequest()
        request.requestedScopes = [.fullName, .email]

        let authorizationController = ASAuthorizationController(authorizationRequests: [request])

        authorizationController.delegate = self
        authorizationController.presentationContextProvider = self

        authorizationController.performRequests()
    }
    
    /// MARK: ASAuthorizationControllerDelegate
    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {

            let userIdentifier = appleIDCredential.user
            let fullName = appleIDCredential.fullName
            let email = appleIDCredential.email
            let realUserStatus = appleIDCredential.realUserStatus

            let identityToken = appleIDCredential.identityToken
            let authCode = appleIDCredential.authorizationCode
            print(userIdentifier,fullName,email,realUserStatus,identityToken ?? "",authCode)

            // Create account in your system
        }
    }

    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        // Handle error.
    }

    /// MARK: ASAuthorizationControllerPresentationContextProviding
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return UIApplication.shared.keyWindow!
    }
  
}
